package com.gxc.config;

import com.gxc.test.AsyncService;
import java.util.concurrent.Executor;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * 测试配置类.
 *
 * @author 宫新程
 * @since 2018/12/17 12:23 AM
 */
//@Configuration
//@ComponentScan("com.gxc.test")
//@EnableAsync
//@EnableWebMvc
public class TestConfigBean implements AsyncConfigurer, WebApplicationInitializer {

  /** 初始化context. */
  public static AnnotationConfigApplicationContext init() {
    return new AnnotationConfigApplicationContext(TestConfigBean.class);
  }

  /** 配置线程池. */
  @Override
  public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    threadPoolTaskExecutor.setCorePoolSize(5);
    threadPoolTaskExecutor.setQueueCapacity(25);
    threadPoolTaskExecutor.setMaxPoolSize(10);
    threadPoolTaskExecutor.initialize();
    return threadPoolTaskExecutor;
  }

  /** 测试 Spring-Aware. */
  //  public static void main(String[] args) {
  //    AnnotationConfigApplicationContext context = init();
  //    new AnnotationConfigApplicationContext(TestConfigBean.class);
  //    AwareService awareService = context.getBean(AwareService.class);
  //    awareService.outPutResource();
  //  }

  /** 测试 线程池. */
  public static void main(String[] args) throws InterruptedException {
    AnnotationConfigApplicationContext context = init();
    AsyncService asyncService = context.getBean(AsyncService.class);
    for (int i = 0; i < 10; i++) {
      asyncService.executeAsycnTask(i);
      asyncService.executeAsycnTaskPlus(i);
    }
    System.out.println(context.getEnvironment().getProperty("os.name"));
    context.close();
  }

  /** 初始化. 放入tomcat中启动. */
  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(TestConfigBean.class);
    context.setServletContext(servletContext);

    ServletRegistration.Dynamic servlet =
        servletContext.addServlet("dispatcher", new DispatcherServlet(context));
    servlet.addMapping("/");
    servlet.setLoadOnStartup(1);
  }
}
